import React, { useRef } from "react";
import { Button, message } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import { PlusOutlined } from "@ant-design/icons";
import ProTable from "@ant-design/pro-table";
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormRadio,
  ProFormDependency,
} from "@ant-design/pro-form";
import { useModel } from "umi";
import { fetchList, updateRole, addRole, remove } from "@/api/role";

import RoleTree from "@/components/RoleTree";

import { disableStatusOptions, platformOptions, miniOptions } from "@/const";
import useRemove from "@/hooks/useRemove";
const modalLayout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
};

const Role = () => {
  const actionRef = useRef();
  const formRef = useRef();
  const { initialState, setInitialState } = useModel("@@initialState");

  // 新增和修改
  const renderModalForm = (type, record) => {
    // type 1=新增 2=修改
    const title = type === 1 ? "新增角色" : "修改角色";

    const handleAddOrUpdate = async (fields) => {
      const postData = {
        ...fields,
        id: record?.role?.id,
        superAdminId: initialState.currentUser?.id,
        hospitalId: initialState.currentUser?.hospitalId,
      };
      let func = addRole;
      if (record?.role?.id) {
        func = updateRole;
      }
      const res = await func(postData);
      if (res.data) {
        message.success(title + "成功");
        if (type === 1) {
          formRef.current?.resetFields();
        }
        actionRef?.current.reload();
        return true; // 关闭弹框
      }
    };

    return (
      <ModalForm
        key="modal"
        formRef={formRef}
        layout="horizontal"
        {...modalLayout}
        title={title}
        width={600}
        trigger={
          type === 1 ? (
            <Button key="button" icon={<PlusOutlined />} type="primary">
              添加
            </Button>
          ) : (
            <Button
              style={{ marginRight: 10 }}
              size="small"
              key="update"
              type="primary"
            >
              编辑
            </Button>
          )
        }
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            formRef.current?.resetFields();
          },
        }}
        onFinish={async (values) => {
          return await handleAddOrUpdate(values);
        }}
        initialValues={{
          ...record?.role,
          platform: record?.platform || 1,
          wechatRoleType: record?.wechatRoleType || 1,
          permissionIds: record?.permissions?.map((item) => item.id),
        }}
      >
        <ProFormText
          label="角色名称"
          name="name"
          rules={[
            { required: true, message: "请输入角色名称" },
            {
              max: 10,
              message: "最长为10位",
            },
          ]}
        />
        <ProFormRadio.Group
          label="平台"
          name="platform"
          options={platformOptions}
          rules={[{ required: true, message: "请选择平台" }]}
          fieldProps={{
            onChange: (e) => {
              formRef.current?.setFieldsValue({
                permissionIds: null,
              });
            },
          }}
        />

        <ProFormDependency name={["platform"]}>
          {({ platform }) => {
            if (platform === 1) {
              return (
                <ProFormRadio.Group
                  label="权限"
                  name="wechatRoleType"
                  options={miniOptions}
                  rules={[{ required: true, message: "请选择权限" }]}
                />
              );
            }
            if (platform === 2) {
              return (
                <ProForm.Item
                  label="权限"
                  name="permissionIds"
                  rules={[{ required: true, message: "请选择权限" }]}
                >
                  <RoleTree />
                </ProForm.Item>
              );
            }
          }}
        </ProFormDependency>
      </ModalForm>
    );
  };

  const columns = [
    {
      title: "序号",
      dataIndex: "index",
      valueType: "index",
      search: false,
    },
    {
      title: "角色名称",
      dataIndex: "name",
      render: (_, record) => {
        return record?.role.name;
      },
      search: false,
    },

    {
      title: "平台",
      dataIndex: "platform",
      search: false,
      render: (_, record) => {
        return record?.role.platform === 1 ? "小程序" : "管理后台";
      },
    },
    {
      title: "角色权限",
      search: false,
      render: (_, record) => {
        const wechatRoleTypeObj = {
          1: "采样员",
          2: "医生",
        };
        if (record?.role.platform === 1) {
          return wechatRoleTypeObj[record?.role.wechatRoleType];
        }

        if (record?.role.platform === 2) {
          return record?.permissions.map((item) => item.name).join("/");
        }
      },
    },

    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      render: (_, record) => [
        renderModalForm(2, record),
        useRemove(remove, record, actionRef, { ids: record.role?.id }),
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey={(record) => record.role.id}
        search={false}
        request={fetchList}
        columns={columns}
        params={{
          hospitalId: initialState.currentUser?.hospitalId,
        }}
        toolBarRender={() => [renderModalForm(1)]}
        // pagination={false}
        // options={false}
      />
    </PageContainer>
  );
};

export default Role;
